package com.example.demo_spring.ioc_di.pureJava.fakeSpring;

import java.lang.reflect.Field;
import java.util.HashMap;

public class SpringFaker {
    private HashMap<String, Object> mBeanContainer;

    public SpringFaker(){
        System.out.println("Constructor: [pureJava_fakeSpring] SpringFaker");
        mBeanContainer = new HashMap<String, Object>();
    }

    public void addCustomer() {
        Customer c = new Customer();
        mBeanContainer.put("customer", c);
    }

    public void addHello() {
        Hello h = new Hello();
        Customer c =  (Customer) mBeanContainer.get("customer");
        h.setCustomer(c); // Spring 框架会通过反射实现，Hello 就不需要提供setCustomer 接口
        mBeanContainer.put("hello", h);
    }

    public Object getBean(String name) {
        return mBeanContainer.get(name);
    }

    public void addHelloWithReflect()
    {
        Customer c =  (Customer) mBeanContainer.get("customer");
        Hello h = setCustomerViaReflect(c);

        mBeanContainer.put("hello", h);
    }

    private Hello setCustomerViaReflect(Customer c){
        Hello targetObject = null;
        try {
            Class<?> tagetClass = Class.forName("com.example.demo_spring.ioc_di.pureJava.fakeSpring.Hello");
            targetObject = (Hello) tagetClass.newInstance();

            Field field = tagetClass.getDeclaredField("mCustomer");
            //为了对类中的参数进行修改我们取消安全检查
            field.setAccessible(true);
            field.set(targetObject, c);

            return targetObject;
        }
        catch (IllegalAccessException e){
            System.out.println("Exception: [pureJava_fakeSpring] IllegalAccessException");
        }
        catch (InstantiationException e){
            System.out.println("Exception: [pureJava_fakeSpring] InstantiationException");
        }
        catch (ClassNotFoundException e){
            System.out.println("Exception: [pureJava_fakeSpring] ClassNotFoundException");
        }
        catch (NoSuchFieldException e){
            System.out.println("Exception: [pureJava_fakeSpring] NoSuchFieldException");
        }

        return targetObject;
    }
}
